<?php

namespace app\parking\controller\admin;

use think\admin\Controller;
use think\Request;
use app\parking\model\ParkingEmployee as EmployeeModel;
use app\parking\model\ParkingCompany as CompanyModel;

class Employee extends Controller
{
    /**
     * 员工管理列表页面
     */
    public function index(Request $request)
    {
        $companyId = $request->get('company_id');
        $this->assign('company_id', $companyId);
        $this->assign('companies', CompanyModel::where('status', 1)->select());
        $this->title = '员工管理';
        return $this->fetch();
    }

    /**
     * 员工管理列表
     */
    public function get(Request $request)
    {
        $companyId = $request->get('company_id');
        $query = EmployeeModel::alias('e')
            ->join('parking_company c', 'e.company_id = c.id')
            ->field('e.*, c.name as company_name')
            ->order('e.id desc');

        // 过滤当前公司员工
        if ($companyId) {
            $query->where('e.company_id', $companyId);
        }

        // 搜索过滤
        if ($plateNumber = $request->get('plate_number')) {
            $query->where('e.plate_number', 'like', "%{$plateNumber}%");
        }

        $data = $query->paginate(10)->toArray();
        return json([
            'code' => 0,
            'msg' => '',
            'count' => $data['total'],
            'data' => $data['data']
        ]);
    }

    /**
     * 添加员工
     */
    public function add(Request $request)
    {
        $companyId = $request->get('company_id');
        $this->assign('company_id', $companyId);
        $this->assign('companies', CompanyModel::where('status', 1)->select());
        return $this->fetch('form');
    }

    /**
     * 保存员工
     */
    public function save(Request $request)
    {
        $data = $request->post();

        if (!isset($data['id']) || empty($data['id'])) {
            $companyId = $data['company_id'];
            $company = CompanyModel::find($companyId);
            $employeeCount = EmployeeModel::where('company_id', $companyId)->count();

            if ($employeeCount >= $company->max_employee_cars) {
                $this->error('当前公司绑定额度已满，请修改公司可绑定员工车辆数');
            }
        }

        if (isset($data['id']) && $data['id']) {
            EmployeeModel::update($data, ['id' => $data['id']]);
            $this->success('员工更新成功');
        } else {
            EmployeeModel::create($data);
            $this->success('员工添加成功');
        }
    }

    /**
     * 编辑员工
     */
    public function edit($id)
    {
        $this->assign('vo', EmployeeModel::find($id));
        $this->assign('companies', CompanyModel::where('status', 1)->select());
        return $this->fetch('form');
    }

    /**
     * 删除员工
     */
    public function delete($id)
    {
        EmployeeModel::destroy($id);
        $this->success('员工删除成功');
    }
}
